/*
 * 类名称:AddressProvinceController.java
 * 包名称:com.lht.controller
 *
 * 修改履历:
 *     日期                       修正者        主要内容
 *     2019-09-30 17:02:56        ZhengZhanWu     初版做成
 */
package com.lht.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lht.admin.annotation.SysLog;
import com.lht.admin.cache.J2CacheUtils;
import com.lht.admin.constants.DataValidConstant;
import com.lht.admin.entity.AddressAreaEntity;
import com.lht.admin.entity.AddressCityEntity;
import com.lht.admin.entity.AddressProvinceEntity;
import com.lht.admin.service.AddressAreaService;
import com.lht.admin.service.AddressCityService;
import com.lht.admin.service.AddressProvinceService;
import com.lht.admin.utils.PageUtils;
import com.lht.admin.utils.R;
import com.lht.admin.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 省份表Controller
 *
 * @author ZhengZhanWu
 * @date 2019-09-30 17:02:56
 */
@RestController
@RequestMapping("addressprovince")
public class AddressProvinceController extends AbstractController {
    private static final int ADDRESS_GET_TYPE_PROVINCE = 1;
    private static final int ADDRESS_GET_TYPE_PROVINCE_CITY = 2;
    private static final int ADDRESS_GET_TYPE_PROVINCE_CITY_AREA = 3;
    private static final String ADDRESS_CACHE_KEY = "address:";
    @Autowired
    private AddressProvinceService addressProvinceService;
    @Autowired
    private AddressCityService addressCityService;
    @Autowired
    private AddressAreaService addressAreaService;

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return R
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("addressprovince:list")
    public R queryAll(@RequestParam Map<String, Object> params) {
        params.put("isDelete", DataValidConstant.IS_DELETE_FALSE_STR);
        List<AddressProvinceEntity> list = addressProvinceService.queryAll(params);

        return R.ok().put("list", list);
    }

    /**
     * 分页查询省份表
     *
     * @param params 查询参数
     * @return R
     */
    @RequestMapping("/list")
    @RequiresPermissions("addressprovince:list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("isDelete", DataValidConstant.IS_DELETE_FALSE_STR);
        Page page = addressProvinceService.queryPage(params);
        PageUtils pageUtil = new PageUtils(page.getRecords(), (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return R
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("addressprovince:info")
    public R info(@PathVariable("id") Long id) {
        AddressProvinceEntity addressProvince = addressProvinceService.getById(id);

        return R.ok().put("addressProvince", addressProvince);
    }

    /**
     * 新增省份表
     *
     * @param addressProvince addressProvince
     * @return R
     */
    @SysLog("新增省份表")
    @PostMapping("/save")
    @RequiresPermissions("addressprovince:save")
    public R save(@RequestBody AddressProvinceEntity addressProvince) {

        addressProvinceService.add(addressProvince);

        return R.ok();
    }

    /**
     * 修改省份表
     *
     * @param addressProvince addressProvince
     * @return R
     */
    @SysLog("修改省份表")
    @PostMapping("/update")
    @RequiresPermissions("addressprovince:update")
    public R update(@RequestBody AddressProvinceEntity addressProvince) {

        addressProvinceService.update(addressProvince);

        return R.ok();
    }

    /**
     * 根据主键删除省份表
     *
     * @param ids ids
     * @return R
     */
    @SysLog("删除省份表")
    @PostMapping("/delete")
    @RequiresPermissions("addressprovince:delete")
    public R delete(@RequestBody Long[] ids) {
        addressProvinceService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 获取地址
     *
     * @param getType 1 = 获取省份 2 = 获取省份城市 3 = 获取城市省份区域
     * @return
     */
    @RequestMapping("/getAddressData")
    public R getAddressData(@RequestParam(defaultValue = "1") int getType) {

        String addressCacheKey = ADDRESS_CACHE_KEY + getType;
        Object address = J2CacheUtils.get(addressCacheKey);
        if (!StringUtils.isNullOrEmpty(address)) {
            List<Map<String, Object>> resultList = JSON.parseObject(address.toString(), new TypeReference<List<Map<String, Object>>>() {
            });
            return R.ok().put("data", resultList);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("isDelete", DataValidConstant.IS_DELETE_FALSE_STR);
        List<AddressProvinceEntity> addressProvinceEntities = addressProvinceService.queryAll(params);
        List<AddressCityEntity> addressCityEntities = addressCityService.queryAll(params);
        List<AddressAreaEntity> addressAreaEntities = addressAreaService.queryAll(params);
        List<Map<String, Object>> provinceList = null;
        List<Map<String, Object>> cityList = null;
        List<Map<String, Object>> areaList = null;
        Map<String, Object> dataMap = null;
        Map<String, Object> cityMap = null;
        Map<String, Object> areaMap = null;
        provinceList = new ArrayList<>();
        for (AddressProvinceEntity addressProvinceEntity : addressProvinceEntities) {
            dataMap = new HashMap<>();
            dataMap.put("value", addressProvinceEntity.getCode());
            dataMap.put("label", addressProvinceEntity.getName());
            List<AddressCityEntity> addressCityEntityList = addressCityEntities.stream().filter(addressCityEntity -> addressProvinceEntity.getCode().equals(addressCityEntity.getProvinceCode())).collect(Collectors.toList());
            cityList = new ArrayList<>();
            if (getType == ADDRESS_GET_TYPE_PROVINCE_CITY) {
                for (AddressCityEntity addressCityEntity : addressCityEntityList) {
                    cityMap = new HashMap<>();
                    cityMap.put("value", addressCityEntity.getCode());
                    cityMap.put("label", addressCityEntity.getName());
                    List<AddressAreaEntity> addressAreaEntityList = addressAreaEntities.stream().filter(addressAreaEntity -> addressCityEntity.getCode().equals(addressAreaEntity.getCityCode())).collect(Collectors.toList());
                    areaList = new ArrayList<>();
                    if (getType == ADDRESS_GET_TYPE_PROVINCE_CITY_AREA) {
                        for (AddressAreaEntity addressAreaEntity : addressAreaEntityList) {
                            areaMap = new HashMap<>();
                            areaMap.put("value", addressAreaEntity.getCode());
                            areaMap.put("label", addressAreaEntity.getName());
                            areaList.add(areaMap);
                        }
                    }
                    cityMap.put("children", areaList);
                    cityList.add(cityMap);
                }
            }
            dataMap.put("children", cityList);
            provinceList.add(dataMap);
        }
        if (CollectionUtils.isNotEmpty(provinceList)) {
            J2CacheUtils.put(addressCacheKey, JSON.toJSONString(provinceList));
        }
        return R.ok().put("data", provinceList);
    }

}
